﻿using UnityEngine;

public class MaxRectSize : NodeSize
{
    public RectTransform rectTransform;
    public float maxWidthRatio;
    public float maxWidth;
    public float maxHeightRatio;
    public float maxHeight;
    public Vector2 rect;
    public Vector2 maxRect;
    public Vector2 offsetRect;

    protected override void OnRefresh(float rw, float rh, float w, float h, float s)
    {
        SetValue(w / h, w, h, s);
    }

    private void SetValue(float ratio, float width, float height, float scale)
    {
        // if (maxWidthRatio > 0)
        // {
        //     if (ratio > maxWidthRatio)
        //     {
        //         if (maxWidth > 0)
        //             SetWidth(maxWidth);
        //         else
        //             SetWidth(width / ratio * maxWidthRatio);
        //     }
        //     else
        //     {
        //         SetWidth(width);
        //     }
        // }
        // else if (maxWidth > 0)
        // {
        //     SetWidth(width > maxWidth ? maxWidth : width);
        // }
        //
        // if (maxHeightRatio > 0)
        // {
        //     if (ratio > maxHeightRatio)
        //     {
        //         SetHeight(height / scale);
        //     }
        //     else
        //     {
        //         if (maxHeight > 0)
        //             SetHeight(maxHeight);
        //         else
        //             SetHeight(height / ratio * maxHeightRatio / scale);
        //     }
        // }
        // else if (maxHeight > 0)
        // {
        //     var ch = height / scale;
        //     SetWidth(ch > maxHeight ? maxHeight : ch);
        // }

        if (maxWidthRatio > 0 || maxWidth > 0)
        {
            SetRect(IsMaxWidth(ratio, width) ? maxRect : rect);
        }

        if (maxHeightRatio > 0 || maxHeight > 0)
        {
            SetRect(IsMaxHeight(ratio, height) ? maxRect : rect);
        }
    }

    bool IsMaxWidth(float ratio, float width)
    {
        if (maxWidthRatio > 0) return ratio > maxWidthRatio;
        if (maxWidth > 0) return width > maxWidth;
        return false;
    }

    bool IsMaxHeight(float ratio, float height)
    {
        if (maxHeightRatio > 0) return ratio > maxHeightRatio;
        if (maxHeight > 0) return height > maxHeight;
        return false;
    }

    protected void SetRect(Vector2 r)
    {
        var _r = r + offsetRect;
        rectTransform.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, _r.x);
        rectTransform.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, _r.y);
    }
}